﻿using Admin.ApplicationLib.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Minio.AspNetCore;

namespace Admin.WebApi.Controllers
{
    [Route("api/v1/files")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IFileService _fileService;
        private readonly MinioOptions _minioOptions;

        public FileController(IFileService fileService,
        IOptions<MinioOptions> options)
        {
            _fileService = fileService;
            _minioOptions = options.Value;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> Upload([FromQuery] string bucketName,
            IFormFile file)
        {
            var stream = file.OpenReadStream();

            byte[] bytes = new byte[stream.Length];
            var _ = await stream.ReadAsync(bytes, 0, bytes.Length);
            //设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);

            MemoryStream memoryStream = new(bytes);
            var data = await _fileService.UploadAsync(memoryStream, bucketName, file.FileName, _minioOptions.Endpoint);
            return Ok(data);
        }
    }
}